/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.meanzoft.minecraft_clone.world;

import java.util.LinkedList;
import org.meanzoft.minecraft_clone.block2.Block;

/**
 *
 * @author Meanz
 */
public class World {

    private Chunk[][][] chunks = new Chunk[128][128][128];

    public World() {
        chunks[0][0][0] = new Chunk(0, 0, 0);
    }

    public void addBlock(int x, int y, int z, Block b) {
        Chunk r = getChunk(x, y, z);
        if (r != null) {
            r.addBlock(x, y, z, b);
        } else {
            System.err.println("Null region");
        }
    }

    public void removeBlock(int x, int y, int z) {
        Chunk r = getChunk(x, y, z);
        if (r != null) {
            r.removeBlock(x, y, z);
        } else {
            System.err.println("Null region (" + x + ", " + y + ", " + z + ")");
        }
    }

    public Block getBlockAt(int x, int y, int z) {
        Chunk r = getChunk(x, y, z);
        if (r != null) {
            return r.getBlock(x, y, z);
        }
        return null;
    }

    public Chunk[] getChunks(int posX, int posY, int posZ, int radius) {
        int chunkX = posX / 16;
        int chunkY = posY / 16;
        int chunkZ = posZ / 16;
        return getSurroundingChunks(chunkX, chunkY, chunkZ, radius);
    }

    public Chunk[] getSurroundingChunks(int chunkX, int chunkY, int chunkZ, int radius) {
        LinkedList<Chunk> _chunks = new LinkedList<Chunk>();

        for (int x = -(radius / 2) + chunkX; x < radius / 2 + chunkX; x++) {
            for (int y = -(radius / 2) + chunkY; y < radius / 2 + chunkY; y++) {
                for (int z = -(radius / 2) + chunkZ; z < radius / 2 + chunkZ; z++) {
                    Chunk c = getChunk(x * 16, y * 16, z * 16);
                    if (c == null) {
                        continue;
                    }
                    _chunks.add(c);
                }
            }
        }

        Chunk[] c = new Chunk[_chunks.size()];
        return _chunks.toArray(c);
    }

    public Chunk getChunk(int x, int y, int z) {
        if (x < 0 || y < 0 || z < 0) {
            return null;
        }
        int chunkSnapX = x / 16;
        int chunkSnapY = y / 16;
        int chunkSnapZ = z / 16;
        if (chunkSnapX > 127 || chunkSnapY > 127 || chunkSnapZ > 127) {
            return null;
        }

        if (chunks[chunkSnapX][chunkSnapY][chunkSnapZ] == null) {
            chunks[chunkSnapX][chunkSnapY][chunkSnapZ] = new Chunk(chunkSnapX, chunkSnapY, chunkSnapZ);
        }
        return chunks[chunkSnapX][chunkSnapY][chunkSnapZ];
    }
}
